/**
*	插件：websocket
*	开发者：雨中磐石
*	地址：www.rockoa.com
*	日期：2023-07-17
*/

js.websocket = {
	getwsurl:function(){
		var url = ''+APIURL;
		if(window['APIURLA']){
			var cd = APIURLA.length,xu = parseInt(Math.random()*cd);
			url = APIURLA[xu];
		}
		return url.replace('http','ws')+'websocket';
	},
	create:function(cans){
		var me = this;
		var defv = js.applyIf(cans,{
			id:'0',
			name:'',
			type:'p',
			url:'',recid:'',
			offline:false,
			isopenoff:true,
			linkci:0,
			onlinksuccess:function(){},
			onmessage:function(){return true;}
		});
		for(var i in defv)this[i]=defv[i];

		this.init = function(){
			if(!this.recid)return;
			if(!this.url || this.url=='auto')this.url = js.websocket.getwsurl();
			importjs('notify');
			var url = this.url+'';
			//url += '?from='+this.recid+'&adminid='+this.type+''+this.id+'&sendname='+jm.base64encode(this.name)+'';
			this.ws = new WebSocket(url);
			this.ws.onerror = function(e){
				me.relink();
			}
			this.ws.onopen = function(){
				me.openws();
			}
			this.ws.onclose= function(){
				me.relink();
			}
			this.ws.onmessage= function(d){
				me.onmessages(js.decode(d.data));
			}
		}
		this.openws = function(){
			this.linkci = 0;
			this.reclear();
			var s = '{"from":"'+this.recid+'","adminid":"'+this.type+''+this.id+'","sendname":"'+this.name+'","atype":"connect"}';
			this.linkbool = true;
			js.msg();
			this.send(s);
			this.onlinksuccess();
		}
		
		this.send = function(s){
			this.ws.send(s);
		}
		
		this.onmessages= function(d){
			this.onmessage(d);
			try{if(window['websocket_onmessage'])window['websocket_onmessage'](d);}catch(e){}
			var type = d.type;
			if(type=='todo'){
				if(d.mess && d.title){
					js.notify.send({
						body:jm.base64decode(d.mess),
						title:jm.base64decode(d.title),
						icon:d.icon,
						click:function(){
							xcy.openxiang({
								num:d.mknum,
								mid:d.mid,
								name:d.mkname,
								cnum:d.cnum,
								funitid:d.funitid,
								ismodal:false
							});
						}
					});
				}
			}
			if(type=='offoline'){
				this.offline = true;
				if(this.isopenoff)js.confirm('服务端在别处连接了，是否重新连接？', function(jg){
					if(jg=='yes'){
						me.relinks(0);
					}
				});
			}
		}
		
		this.relink = function(){
			this.linkbool = false;
			this.reclear();
			if(this.offline)return;
			js.msg('msg','服务端连接已断开<span id="timevsse">0</span>秒后重连', 60);
			this.linkci ++;
			this.relinks(3 * this.linkci);
			if(this.linkci == 10)this.linkci = 0;
		}
		
		this.reclear = function(){
			clearTimeout(this.relinktime);
		}
		
		this.relinks = function(sj){
			this.reclear();
			if(sj==0){
				this.offline = false;
				js.msg('wait','连接中...');
				this.init();
				return;
			}
			$('#timevsse').html(sj+'');
			this.relinktime = setTimeout(function(){me.relinks(sj-1)}, 1000);
		}
		
		this.init();
	}
}